<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Http\Model\Documents as DocumentsModel;
use DB;

class HandleDataSource extends Command
{
    protected $documentsModel;

    /**
     * 文件夹路径
     * @var string
     */
    protected $phphtml_path;

    /**
     * 文件总数
     * @var int
     */
    protected $filetotal = 13605;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'dataSource:handle';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '读取目录名保存到数据库';

    /**
     * Create a new command instance.
     *
     * handleDataSource constructor.
     */
    public function __construct()
    {
        parent::__construct();

        $this->documentsModel = new DocumentsModel();
        $this->phphtml_path = base_path('resources/phphtml');
    }

    /**
     * 命令执行入口
     * @throws \Exception
     */
    public function handle()
    {
        $progressHandle = $this->output->createProgressBar($this->filetotal);

        try{
            $handle = opendir($this->phphtml_path);
            if (!$handle) {
                throw new \Exception('打开目录失败！');
            }
            while (($file = readdir($handle)) !== false) {
                if (!$file || $file == '.' || $file == '..' || (strpos($file, '.') === 0)) {
                    continue;
                }
                $file_name = substr($file, 0, strrpos($file, '.'));

                $data = ['file_name'=>$file_name];
                $res = $this->documentsModel->addData($data);
                if (!$res) {
                    throw new \Exception("{$file_name}保存失败！");
                }

                $progressHandle->advance();
                dump("{$file_name}保存成功！");
            }

        } catch (Exception $e){
            echo $e->getMessage();
        }

        /*DB::table('documents')->orderBy('id')->chunk('100', function($info) {
           foreach ($info as $val) {
               $res = DB::table('documents')->where('id', $val->id)->update(['content'=>htmlspecialchars($val->content), 'update_time'=>date('Y-m-d H:i:s')]);
               dump($res);exit;
           }
        });*/


        $progressHandle->finish();
    }
}
